﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Extensions;
using DotNet.Auth.WebUtility;
using DotNet.Helper;
using System.Text;
using DotNet.Collections;
using DotNet.Core.Service;
using DotNet.JCore.Service;
using DotNet.Auth.Utility;

namespace DotNet.Web
{
    public static class HtmlExtensions
    {
        /// <summary>
        /// 激活的ActionCSS类
        /// </summary>
        public static MvcHtmlString ActiveActionClass(this HtmlHelper helper, string action, string cls)
        {
            var dic = helper.ViewContext.RouteData.Values;
            if (dic.ContainsKey("action") && dic["action"].ToStringOrEmpty().Equals(action, StringComparison.OrdinalIgnoreCase))
            {
                return MvcHtmlString.Create(cls);
            }
            return MvcHtmlString.Empty;
        }

        /// <summary>
        /// 获取投诉建议分类下拉选项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected">选中的值</param>
        public static MvcHtmlString FeedbackCategoryOption(this HtmlHelper helper, string selected = null)
        {
            return MvcHtmlString.Create(AuthWebHelper.BuildItemOption("FeedbackCategory", selected));
        }

        /// <summary>
        /// 获取文章分类下拉选项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected">选中的值</param>
        public static MvcHtmlString ArticleCategoryOption(this HtmlHelper helper, string selected = null)
        {
            var list = ArticleCategoryService.Instance.GetSimpleList();
            return MvcHtmlString.Create(WebHelper.GetSelectOptions(list, selected, false));
        }

        /// <summary>
        /// 获取检查点下拉选项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected">选中的值</param>
        public static MvcHtmlString CheckPointsCategoryOption(this HtmlHelper helper, string selected = null)
        {
            var list = new CheckPointsService().GetSimpleList();
            list.Insert(0, new Utility.Simple(" ", "所有稽查点"));
            var currentUser = AuthHelper.GetSessionUser();
            var currentUserId = currentUser.Id;
            if (!currentUser.IsAdmin)
            {
                var emp = new EmployeeService().GetByUserId(currentUserId);
                if (emp != null)
                {
                    var pointId = emp.PointId;
                    list.Delete(p => p.Id != pointId);
                    if (selected == null)
                    {
                        selected = pointId;
                    }
                }
            }
            return MvcHtmlString.Create(WebHelper.GetSelectOptions(list, selected, false));
        }
        /// <summary>
        /// 获取检查点下拉选项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected">选中的值</param>
        public static MvcHtmlString CheckPointsCategoryOption_Name(this HtmlHelper helper, string selected = null)
        {
            var list = new CheckPointsService().GetSimpleList();
            list.Insert(0, new Utility.Simple(" ", "全部稽查点"));
            var currentUser = AuthHelper.GetSessionUser();
            var currentUserId = currentUser.Id;
            if (!currentUser.IsAdmin)
            {
                var emp = new EmployeeService().GetByUserId(currentUserId);
                if (emp != null)
                {
                    var pointId = emp.PointId;
                    list.Delete(p => p.Id != pointId);
                    if (selected == null)
                    {
                        selected = pointId;
                    }
                }
            }
            foreach (var item in list)
            {
                item.Id = item.Name;
            };
            return MvcHtmlString.Create(WebHelper.GetSelectOptions(list, selected, false));
        }

        /// <summary>
        /// 获取所有检查点下拉选项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected">选中的值</param>
    
        public static MvcHtmlString CheckPointsCategoryOptionALL(this HtmlHelper helper, string selected = null)
        {
            var list = new CheckPointsService().GetSimpleList();
            list.Insert(0, new Utility.Simple(" ", "所有稽查点"));
            var currentUser = AuthHelper.GetSessionUser();
            var currentUserId = currentUser.Id;
            var emp = new EmployeeService().GetByUserId(currentUserId);
            var pointId = emp.PointId;
            selected = pointId;
          
            return MvcHtmlString.Create(WebHelper.GetSelectOptions(list, selected, false));
        }


        /// <summary>
        /// 获取颜色下拉选项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected">选中的值</param>
        public static MvcHtmlString CarColorCategoryOption(this HtmlHelper helper, string selected = null)
        {
            return MvcHtmlString.Create(AuthWebHelper.BuildItemOption("CarColor", selected));
        }


        /// <summary>
        /// 获取客运站下拉选项
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected">选中的值</param>
        public static MvcHtmlString StationCategoryOption(this HtmlHelper helper, string selected = null)
        {
            return MvcHtmlString.Create(AuthWebHelper.BuildItemOption("Station", selected));
        }


        /// <summary>
        /// 生成分页
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="source">数据源</param>
        public static MvcHtmlString Pages<T>(this HtmlHelper helper, PageList<T> source)
        {
            if (source == null || source.Count <= 0)
            {
                return MvcHtmlString.Empty;
            }

            var pagetemplate = @"
<div class=""mtNext"">
    <ul>
        {0}
    </ul>
    <div class=""clear""></div>
</div>";
            int showPages = 11;
            int pageIndex = source.PageIndex;
            int totalPages = source.TotalPages;

            //string pagedInfo = string.Empty;
            //string pagedInfo = (source.RecordEndIndex == 0 && source.RecordEndIndex == 0) ?
            //    $"共 {source.TotalCount} 条" :
            //    $"共 {source.TotalCount} 条 当前显示 {source.RecordStartIndex} 到 {source.RecordEndIndex} 条";

            if (totalPages <= showPages)
            {
                return MvcHtmlString.Create(string.Format(pagetemplate, BuildPage(helper, 1, totalPages, pageIndex)));
            }

            var pages = new StringBuilder();

            if (pageIndex <= 7)
            {
                pages.Append(BuildPage(helper, 1, 10, pageIndex));
                pages.Append("<li class=\"disabled\"><span>···</span></li>");
                pages.Append(BuildPage(helper, totalPages, totalPages, pageIndex));
            }
            else if (pageIndex >= (totalPages - 7))
            {
                pages.Append(BuildPage(helper, 1, 1, pageIndex));
                pages.Append("<li class=\"disabled\"><span>···</span></li>");
                pages.Append(BuildPage(helper, totalPages - 10, totalPages, pageIndex));
            }
            else
            {
                pages.Append(BuildPage(helper, 1, 1, pageIndex));
                pages.Append("<li class=\"disabled\"><span>···</span></li>");
                pages.Append(BuildPage(helper, pageIndex - 5, pageIndex + 5, pageIndex));
                pages.Append("<li class=\"disabled\"><span>···</span></li>");
                pages.Append(BuildPage(helper, totalPages, totalPages, pageIndex));
            }


            return MvcHtmlString.Create(string.Format(pagetemplate, pages));
        }

        /// <summary>
        /// 生成页面链接
        /// </summary>
        private static string BuildPage(HtmlHelper helper, int start, int end, int currentPageIndex)
        {
            var routeData = helper.ViewContext.RouteData.Values;
            var queryString = HttpContext.Current.Request.QueryString;
            foreach (string key in queryString.Keys)
            {
                if (queryString[key] != null && !string.IsNullOrEmpty(key))
                {
                    routeData[key] = queryString[key];
                }
            }
            string controller = routeData["controller"].ToString();
            string action = routeData["action"].ToString();
            var sb = new StringBuilder();
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
            for (int i = start; i <= end; i++)
            {
                routeData["page"] = i;
                //var url = helper.ActionLink($"{i}", action, controller, routeData, null);
                sb.Append(currentPageIndex == i
                    ? $"<li class=\"mtNextHov\" title=\"第{i}页\"><span>{i}</span></li>"
                    : $"<a href=\"{url.Action(action, controller, routeData)}\"><li title=\"第{i}页\">{i}</li></a>");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获取Request.Form参数或者Request.QueryString参数值
        /// </summary>
        /// <param name="name">参数名称</param>
        public static string Q(this HtmlHelper helper, string name, string defaultValue = "")
        {
            return WebHelper.GetParamString(name, defaultValue);
        }
        /// <summary>
        /// 稽查登记状态
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected"></param>
        /// <returns></returns>
        public static MvcHtmlString CheckStatusCategoryOption(this HtmlHelper helper, string selected = null)
        {
            //string selected = intselected.ToString();
            return MvcHtmlString.Create(AuthWebHelper.BuildItemOption("CheckStatus", selected));
        }
        /// <summary>
        /// 处理状态
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected"></param>
        /// <returns></returns>
        public static MvcHtmlString ProcessStatusCategoryOption(this HtmlHelper helper, int intselected = 0)
        {
            string selected = intselected.ToString();
            return MvcHtmlString.Create(AuthWebHelper.BuildItemOption("ProcessStatus", selected));
        }
        /// <summary>
        /// 违规内容
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="selected"></param>
        /// <returns></returns>
        public static MvcHtmlString OffenceIdCategoryOption(this HtmlHelper helper, string selected = null)
        {
            return MvcHtmlString.Create(AuthWebHelper.BuildItemOption("OffenceId", selected));
        }

        /// <summary>
        /// 自定义样式（运行时间）
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="runTime">运行时间</param>
        /// <param name="time">系统设置时间：默认为120分钟</param>
        /// <param name="color">颜色：默认为red</param>
        /// <returns></returns>
        public static MvcHtmlString TimeOutSpan(this HtmlHelper helper, int runTime, int time = 120, string color = "red")
        {
            if (runTime > time)
            {
                if (runTime > 120)
                {
                    return MvcHtmlString.Create($"<span style=\"color: {color}; font - weight:bold\" >大于2小时</span>");
                }
                else
                {
                    return MvcHtmlString.Create($"<span style=\"color: {color}; font - weight:bold\" >{runTime}(分钟)</span>");
                }
            }
            else
            {
                return MvcHtmlString.Create($"<span>{runTime}(分钟)</span>");
            }
        }

    }
}